import {
    TYPES
} from '../reducers/selfordingReducers';
import {
    Alert,
    AsyncStorage
} from 'react-native';
import ProductModel from '../model/catalog/category';
import _ from 'lodash';
import hash from 'object-hash';
import {BigNumber} from 'bignumber.js'
let zeroNumberControl = new BigNumber(0);
let product = new ProductModel();
import Http from '../utils/http';
const http = new Http();
import {i18n} from '../i18n';

export function getItem(key){
    return (dispatch, getState) => {
        return AsyncStorage.getItem(key,(Error,result)=>{
            if (result === null){
                dispatch(getBackdata({}))
            } else {
                const jsonValue = JSON.parse(result);
                console.log(jsonValue)
                dispatch(getBackdata(jsonValue))
            }
        })
    }
}
export function getBackdata(storeinfo) {
    return {
        type: TYPES.APPDATA,
        storeinfo
    }
}

export function getList() {
    return (dispatch, getState) => {
        dispatch({
            type: TYPES.ISLOADING,
            loading: true
        })
        getIndexMenu(dispatch);
    }
}

function getIndexMenu(dispatch) {
    product.getCategoryProducts()
        .then((res) => {
            res=Array.isArray(res)? res:[];
            res.map((item,index)=>{
                (Array.isArray(item.products)? item.products:[]).map((items,idx)=>{
                    (Array.isArray(items.options)? items.options:[]).map((val,k)=>{
                        Array.isArray(val.values)&& val.values.map((subval,j)=>{
                            if(val.required==1&&j==0){
                                subval.selected=true
                            }
                        })
                    })
                })
            })
            res.push('');
            var rdata = res;
            dispatch({
                type: TYPES.GOODSLIST,
                categoryArr: rdata,
                topage: 0
            })
        }).catch((e) => {
            console.log(e);
            dispatch({
                type: TYPES.ISLOADING,
                loading: false
            })
            Alert.alert("Fetail", "network err!please try again!", [{
                text: "OK",
                onPress: () => {
                    getIndexMenu(dispatch);
                }
            }])
        })

}
export function Addcart() {
    return ((dispatch, getState) => {
        let {
            detailInfo,
            cartArr,
            count,
            storeinfo:{tax_rate},
        } = getState().selfcart;
        let optionsPrice = 0; //单个附加的金额
        let price = Number(detailInfo["price"]);
        detailInfo.options.map((item,index)=>{//去掉未选的
            item.values.map((items,idx)=>{
                if(!items.selected){
                    item.values.splice(idx,1)
                }
            })
        })  
        detailInfo.options.map(item=>{//附加的金额
            item.values.map(vals=>{
                optionsPrice = zeroNumberControl.plus((vals["price_prefix"] == "+" ? vals["price"]:-(vals["price"]))).toNumber();
            })
        });
        var cartItem = {
            name: detailInfo["name"],
            image: detailInfo["image"],
            product_id: detailInfo["product_id"],
            price:  Number(detailInfo["price"]),
            options: detailInfo["options"],
            optionsPrice:zeroNumberControl.plus(optionsPrice).toNumber(),
            ntotalprice:zeroNumberControl.plus(price).multipliedBy(count).toNumber(),
            totaloptionsPrice:zeroNumberControl.plus(optionsPrice).multipliedBy(count).toNumber(),
            optionHash: hash(detailInfo["options"]),
            'count': count
        }
        let isPush = true; //是否为新加的商品
        let totalPrice=0;//小计
        let totalTax=0;
        tax_rate=tax_rate&&(tax_rate.value||0);//税费
        tax_rate=zeroNumberControl.plus(tax_rate).dividedBy(100).toNumber();//税率
        let combined=0;//合计
        cartArr = cartArr.map(item => {
            if (item["product_id"] == cartItem["product_id"] && item["optionHash"] == cartItem["optionHash"]) {
                item["count"] = item["count"] + cartItem["count"];
                item["totaloptionsPrice"]=zeroNumberControl.plus(item["totaloptionsPrice"]).plus(cartItem["totaloptionsPrice"]).toNumber();
                item["ntotalprice"]=zeroNumberControl.plus(item["ntotalprice"]).plus(cartItem["ntotalprice"]).toNumber();
                isPush = false;
            }
            totalPrice = zeroNumberControl.plus(totalPrice).plus(item["ntotalprice"]).plus(item["totaloptionsPrice"]).toNumber();
            return { ...item
            }
        })
        if (isPush) {
            cartArr.push(cartItem)
            totalPrice = zeroNumberControl.plus(totalPrice).plus(cartItem["ntotalprice"]).plus(cartItem["totaloptionsPrice"]).toNumber();
        }
        totalTax=zeroNumberControl.plus(totalTax).plus(tax_rate).multipliedBy(totalPrice).toFixed(2);
        dispatch({
            type: TYPES.ADDCART,
            combined:zeroNumberControl.plus(combined).plus(totalPrice).plus(totalTax).toFixed(2),
            totalPrice,
            totalTax,
            cartArr,
            count: 1
        })
    })
}

export function CartNum(count, type) {
    return ((dispatch, getState) => {
        if (count > 999) {
            return Alert.alert("Fetail", "Maximum number 999?");
        } else {
            if (type == "reduction" && count == 1) {
                return Alert.alert("Fetail", "Miniimum number 1?")
            }
            var numbers = (type == "add" ? ++count : (count == 1 ? 1 : --count));
            dispatch({
                type: TYPES.CARTNUM,
                count: numbers
            })
        }
    })
}

export function skuselected(option_id, value_id, idx, index) {
    return ((dispatch, getState) => {
        var {
            detailInfo
        } = getState().selfcart;
        if (detailInfo.options[idx]['values'][index].selected == true&&detailInfo.options[idx].required==0) {
            detailInfo.options[idx]['values'][index].selected=false;
        }else if(detailInfo.options[idx]['values'][index].selected == true&&detailInfo.options[idx].required==1){
            return;
        }else{
            detailInfo.options[idx]['values'].map((item, k) => {
                if (item.value_id == value_id) {
                    item.selected = true
                } else {
                    item.selected = false;
                }
            })
        }
        dispatch({
            type: TYPES.SKUSELECTED,
            detailInfo: detailInfo,
        })
    })

}


export function Tapgoods(detailInfo) {
    var detailInfo = _.cloneDeep(detailInfo);
    return ((dispatch, getState) => {
        dispatch({
            type: TYPES.TAPGOODS,
            detailInfo,
        })
    })
}


export function Changeindex(obj) {
    return ((dispatch, getState) => {
        var {
            categoryArr,
            topage
        } = getState().selfcart;
        if (obj.i == topage) {
            return;
        }
        if (obj.i == categoryArr.length - 1) {
            dispatch({
                type: TYPES.CHANGEINDEX,
                checkoutmodel:true,
                topage: obj.i
            })
        } else {
            dispatch({
                type: TYPES.CHANGEINDEX,
                checkoutmodel:false,
                topage: obj.i,
            })

        }
    })
}
export function setModalVisible(visible, name) {
    return ((dispatch, getState) => {
        var {
            categoryArr
        } = getState().selfcart;
        if (topage == categoryArr.length - 1) {
            return
        };
        if (name == 'checkoutmodel' && visible) {
            var topage = categoryArr.length - 1;
            dispatch({
                type: TYPES.INITPAGE,
                topage: topage
            })
        }
        dispatch({
            type: TYPES.SETMODALVISIBLE,
            visible: visible,
            name: name
        })

    })
}

export function delCartitem(cartItem) {
    return ((dispatch, getState) => {
        var {
            cartArr,
            storeinfo:{tax_rate},
        } = getState().selfcart;
        let totalPrice=0;//小计
        let totalTax=0;//税费
        let combined=0;//合计
        tax_rate=tax_rate&&(tax_rate.value||0);//税费
        tax_rate=zeroNumberControl.plus(tax_rate).dividedBy(100).toNumber();//税率
        cartArr.map((item, index) => {
            if (item["product_id"] == cartItem["product_id"] && item["optionHash"] == cartItem["optionHash"]) {
                cartArr.splice(index, 1);
            }else{
                totalPrice = zeroNumberControl.plus(totalPrice).plus(item["ntotalprice"]).plus(item["totaloptionsPrice"]).toNumber();
                totalTax = 0;
            }
        })
        totalTax=zeroNumberControl.plus(totalTax).plus(tax_rate).multipliedBy(totalPrice).toFixed(2);
        dispatch({
            type: TYPES.ADDCART,
            combined:zeroNumberControl.plus(combined).plus(totalPrice).plus(totalTax).toFixed(2),
            totalPrice,
            totalTax,
            cartArr,
            count: 1
        })
    })
}

export function changeCartnum(cartItem, type) {
    return ((dispatch, getState) => {
        var {
            cartArr,
            storeinfo:{tax_rate},
        } = getState().selfcart;
        let totalPrice=0;//小计
        let totalTax=0;//税费
        let combined=0;//合计
        tax_rate=tax_rate&&(tax_rate.value||0);//税费
        tax_rate=zeroNumberControl.plus(tax_rate).dividedBy(100).toNumber();//税率
        cartArr.map((item, index) => {
            if (item["product_id"] == cartItem["product_id"] && item["optionHash"] == cartItem["optionHash"]) {
                if (type == "add") {
                    if (item["count"] == 999) {
                        Alert.alert("Fetail", "Maximum number 999?");
                    } else {
                        item["count"] = item["count"] + 1;
                        item["totaloptionsPrice"]=zeroNumberControl.plus(item["totaloptionsPrice"]).plus(item['optionsPrice']).toNumber();
                        item["ntotalprice"]=zeroNumberControl.plus(item["ntotalprice"]).plus(item['price']).toNumber();
                    }
                } else {
                    if (item["count"] == 1) {
                        Alert.alert("Fetail", "Miniimum number 1?")
                    } else {
                        item["count"] = item["count"] - 1;
                        item["totaloptionsPrice"]=zeroNumberControl.plus(item["totaloptionsPrice"]).minus(item['optionsPrice']).toNumber();
                        item["ntotalprice"]=zeroNumberControl.plus(item["ntotalprice"]).minus(item['price']).toNumber();
                    }
                }
            }
            totalPrice = zeroNumberControl.plus(totalPrice).plus(item["ntotalprice"]).plus(item["totaloptionsPrice"]).toNumber();
        })
        totalTax=zeroNumberControl.plus(totalTax).plus(tax_rate).multipliedBy(totalPrice).toFixed(2);
        dispatch({
            type: TYPES.ADDCART,
            combined:zeroNumberControl.plus(combined).plus(totalPrice).plus(totalTax).toNumber(),
            totalPrice,
            totalTax,
            cartArr,
            count: 1
        })
    })

}

export function diningType(name){//就餐方式
    return ((dispatch, getState) => {
    dispatch({
        type: TYPES.DININGTYPE,
        diningtype:name
    })
 })
}

export function placeOrder(name,callBack){
    return (dispatch,getState)=>{
        var {diningtype,cartArr,placeloading}= getState().selfcart;
        if(placeloading){
            return;
        }
        if(cartArr.length==0){
            return  Alert.alert("Fetail", "Please select the goods!")
        }
        changePlaceloading(true)(dispatch);
        var products=[];
        cartArr.map((item,index)=>{
            var options=[];
            Array.isArray(item.options) && item.options.forEach((items,indexs)=>{
                items.values.forEach((lists,idx)=>{
                if(lists.selected==true){
                    options[indexs]={};
                    options.push({
                        optionId:items.server_option_id,
                        valueId:lists.server_value_id
                    })
                }
                })
            })
            products.push({
                "productId":item.product_id,
                "seatId":0,
                "qty":item.count,
                "options":options
            })
        })
        var payjosn={
            "paymentMethod":name,
            "paymentTime":"now",
            "takeOption":diningtype,
            "products":products,
            "deskId":0
        }
        http.post("checkoutOrderPlace",{data:JSON.stringify(payjosn)})
        .then((res)=>{
            changePlaceloading(false)(dispatch);
            console.log(res);
            //TODO 这里返回数据错误,删除购物车
            // if(res.status){
                    clearCart(dispatch);
                    callBack && callBack(639);
            // }else{
            //     Alert.alert(i18n.t("appName"),res.message [{
            //         text: "OK"
            //     }]);
            // }
        })
        .catch((e)=>{
            console.log(e);
            //TODO 测试
            callBack && callBack(639);
            // dispatch({
            //     type:TYPES.CHANGEPLACEORDERING,
            //     placeloading:false
            // })
            // Alert.alert("Fetail", "network err! please try again!", [{
            //     text: "OK"
            // }])
        })
    }
}

function clearCart(dispatch){
    dispatch({
        type: TYPES.ADDCART,
        combined:0,
        totalPrice:0,
        totalTax:0,
        cartArr:[],
        count: 0
    })
}

export function payOrder(params,callBack = null){
    return (dispatch,getState)=>{
        let body = {
            method:params.name == 'cash'?"cash":"swipe",
            order_id:params.orderId,
            amount:0.01,
            tax_amount:0.01,
            tip_amount:0.01,
            tip_percentage:0,
            sort_order:0,
            ...params.extaData
        };
        http.post("checkoutOrderPay",body)
        .then((res)=>{
            changePlaceloading(false)(dispatch);
            console.log(res);
            if(res.status){
                Alert.alert(i18n.t("appName"),"OK");
                //TODO 
                clearCart(dispatch);
                callBack && callBack(true);
            }else{
                callBack(false);
                Alert.alert(i18n.t("appName"),res.message);
            }
        })
        .catch((e)=>{
            changePlaceloading(false)(dispatch);
            Alert.alert("Fetail", "network err! please try again!", [{
                text: "OK"
            }])
        })
    }
}

export function changePlaceloading(placeloading = false){
    return (dispatch)=>{
        dispatch({
            type:TYPES.CHANGEPLACEORDERING,
            placeloading
        })
    }
}